package com.zjy.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjy.pojo.User;
import com.zjy.service.impl.MemberServiceimpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Zhengjz
 * @version 1.0
 * @className MemberController
 * @date 2021/1/22 12:14
 */
@Controller
public class MemberController {


    @Autowired
    private MemberServiceimpl memberServiceimpl;

    @RequestMapping("/member/list")
    public String memberList(Model model, Integer pageNum,HttpServletRequest request){

       if(pageNum == null){
           pageNum = 1;
       }

        //当前第几页，每页显示5条数据
        PageHelper.startPage(pageNum, 5);
        List<User>  list = memberServiceimpl.list();
        PageInfo  pageInfo =  new PageInfo<>(list);

        model.addAttribute("pageInfo",pageInfo);
        request.getSession().setAttribute("pagenum",pageNum);
        return "member/member-list";
    }


    //导出数据
    @RequestMapping("/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        Integer pageNum = (Integer) request.getSession().getAttribute("pagenum");

        Workbook workbook = memberServiceimpl.exportUser(pageNum);
        try {
            //设置响应头
            response.setContentType("application/octet-stream");//所有文件都支持
            String fileName = "员工信息.xls";
            fileName = URLEncoder.encode(fileName,"utf-8");
            response.setHeader("content-disposition","attachment;filename="+fileName);
            //文件下载
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
